package com.ifp.opengate.boot.utils;

import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ifp.adapter.message.field.MessageField;
import com.ifp.adapter.message.head.DefaultHead;
import com.ifp.core.util.SpringContextsUtil;

/**
 * 交互平台返回报文头多余字段处理
 * 
 * @author zhy
 *
 */
public class HeaderToBodyUtil {
    // 定义了需要抽取的header中的字段的beanid
    private final static String RESPONSE_DEADER = "jhHttpResponseHead";

    public static String headerToBody(String str) {
        DefaultHead httpResponseHead = (DefaultHead)SpringContextsUtil.getBean(RESPONSE_DEADER);
        List<MessageField> fieldList = httpResponseHead.getFieldOrder();
        JSONObject backJson = JSONObject.parseObject(str);
        String header = backJson.getString("responseHeader");
        HashMap<String, String> headerMap = JSONObject.parseObject(header, HashMap.class);
        String body = backJson.getString("responseBody");
        HashMap<String, String> bodyMap = JSONObject.parseObject(body, HashMap.class);
        // 如果header里面包含了设定的字段，把字段加入body
        for (String standardKey : headerMap.keySet()) {
            if (fieldList.contains(standardKey)) {
                bodyMap.put(standardKey, headerMap.get(standardKey));
            }
        }

        String bodyStr = JSONObject.toJSONString(bodyMap);
        String headerStr = JSONObject.toJSONString(headerMap);
        String returnStr = "{\"responseHeader\":" + headerStr + ",\"responseBody\":" + bodyStr + "}";
        return returnStr;
    }
}
